﻿using CompanyHubServer.DAL;
using CompanyHubServer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http;

namespace CompanyHubServer.Controllers
{
    public class DataController : ApiController
    {
        private HubContext db = new HubContext();

        [HttpGet]
        [ActionName("AppToken")]
        public AppToken GetCurrentAppToken()
        {
            var token =  db.AppTokens.Where(c => c.IsActive).FirstOrDefault();

            if (token != null)
            {
                token.SourceUri = CreateAppDataPath(token.SourceUri);
            }

            return token;
        }

        [HttpGet]
        [ActionName("CompanyHub")]
        public Package GetCurrentCompanyHub()
        {
            var hub = db.Packages.Where(p => p.IsCompanyHub && p.IsActive && !p.IsHistory).FirstOrDefault();

            if (hub != null)
            {
                UpdatePackageUrls(ref hub);
            }

            return hub;
        }

        [HttpGet]
        [ActionName("Packages")]
        public IEnumerable<Package> GetAllCurrentPackages()
        {
            var pkgs = db.Packages.Where(p => !p.IsHistory && p.IsActive).OrderBy(p => p.Title).ToList();

            if (pkgs != null)
            {
                for(int i=0;i<pkgs.Count();i++)
                {
                    var pkg = pkgs[i];
                    UpdatePackageUrls(ref pkg);
                }
            }
            return pkgs;
        }

        private void UpdatePackageUrls(ref Package pkg)
        {
            pkg.SourceUri = CreateAppDataPath(pkg.SourceUri);
            pkg.Thumbnail = CreateAppDataPath(pkg.Thumbnail);
        }

        private string CreateAppDataPath(string fileName)
        {
            var url = HttpContext.Current.Request.Url;

            return String.Format("{0}://{1}:{2}{3}",
                url.Scheme,
                url.Host,
                url.Port,
                VirtualPathUtility.ToAbsolute("~/Downloads/" + fileName));

        }


    }
}
